# 接口请求的工具
import allure
import requests
from loguru import logger
import conftest
from common import log_util  # 导入日志工具模块
from common.assert_util import responsetime


def send_request(
        method,
        path,
        name=None,
        params=None,
        data=None,
        headers=None,
        cookies=None,
        files=None,
        auth=None,
        timeout=None,
        allow_redirects=True,
        proxies=None,
        hooks=None,
        stream=None,
        verify=None,
        cert=None,
        json=None,
        **kwargs
                 ):
    """
    对requests进行二次封装，如果需要传name实参，请使用关键字传参
    :param method:
    :param path:
    :param name: 你自定义被测接口的名字
    :param params:
    :param data:
    :param headers:
    :param cookies:
    :param files:
    :param auth:
    :param timeout:
    :param allow_redirects:
    :param proxies:
    :param hooks:
    :param stream:
    :param verify:
    :param cert:
    :param json:
    :param kwargs:
    :return: response对象
    """
    try:
        data ={
            'url':conftest.base_url+path,
            'method':method,
            'params':params,
            'data':data,
            'json':json,
            'headers':headers,
            'cookies':cookies,
            'files':files,
            'auth':auth,
            'timeout':timeout,
            'allow_redirects':allow_redirects,
            'proxies':proxies,
            'hooks':hooks,
            'stream':stream,
            'verify':verify,
            'cert':cert
        }
        # 运行所有用例使用一个会话
        res = requests.session().request(**data)
        # 记录接口的请求信息
        logger.info(
            f'测试接口：----------------------------------------------------------------{name}----------------------------------------------------------------')
        logger.info(f'请求地址：{res.request.url}')
        logger.info(f'请求方式：{res.request.method}')
        logger.info(f'请求头：{res.request.headers}')
        logger.info(f'请求体：{res.request.body}')
        logger.info(f'请求的响应时间：{responsetime(res)}')

        # 记录接口的响应信息
        logger.info(f'HTTP状态码：{res.status_code}')
        logger.info(f'HTTP状态信息：{res.reason}')
        logger.info(f'响应头：{res.headers}')
        logger.info(f'响应体：{res.text}')

        # 记录接口的请求信息
        request_data={
            "URL":res.request.url,
            "Method":res.request.method,
            "Headers":res.request.headers,
            "Body":res.request.body
        }

        response_data = {
            "Status Code":res.status_code,
            "Message":res.reason,
            "Headers":res.headers,
            "Body":res.text,
            "Response Time":f'{responsetime(res)}ms'
        }
        def format_data(dict_package):
            formatted_data = '' # 初始化格式化后的数据
            for k,v in dict_package.items():
                formatted_data+=f"{k}:\n{v}\n\n"
            return formatted_data

        # 将接口的请求响应信息添加到allure报告中
        allure.attach(format_data(request_data),name='接口的请求信息',attachment_type=allure.attachment_type.TEXT)
        allure.attach(format_data(response_data), name='接口的响应信息', attachment_type=allure.attachment_type.TEXT)

    except requests.RequestException as e:
        logger.error(f'接口请求失败：{str(e)}')
        raise e
    return res
